<template>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    @confirm="onSubmit"
    :confirmBtn="{
        content: loading?'提交中...':'确认',
        theme: 'primary',
        loading: loading,
      }"
    width="800px"
    top="5%"
  >
    <t-form ref="form" :colon="true"  :data="formData" labelWidth="100px" :rules="rules">
      <t-row style="row-gap:24px">
        <t-col :span="12">
<!--          <t-form-item label="子系统" name="sex">-->
<!--            <t-select placeholder="请选择子系统"  v-model="formData.serviceId">-->
<!--              <t-option-->
<!--                v-for="(item,index) in serviceList" :value="item.id" :key="index" :label="item.serviceName"-->
<!--              ></t-option>-->
<!--            </t-select>-->
<!--          </t-form-item>-->
        </t-col>
        <t-col :span="12">

          <t-form-item :rules='[
          { required: true, message: "上级菜单不能为空" }
          ]' v-if="parentId>0" label="上级菜单" name="parentId">
            <t-tree-select clearable  :treeProps="{keys: {value: 'id',label:'menuName'}}"  v-model="formData.parentId" :data="menuOptions" placeholder="选择上级菜单"></t-tree-select>
          </t-form-item>
          <t-form-item v-else label="上级菜单" name="parentId">
            <t-tree-select clearable  :treeProps="{keys: {value: 'id',label:'menuName'}}"  v-model="formData.parentId" :data="menuOptions" placeholder="选择上级菜单,不选则为最高级"></t-tree-select>
          </t-form-item>
        </t-col>
        <t-col :span="12" >
          <t-form-item label="菜单类型" name="menuType">
            <t-radio-group v-model="formData.menuType">
              <t-radio value="M" label="目录"></t-radio>
              <t-radio value="C" label="菜单"></t-radio>
              <t-radio value="CC" label="菜单子页面"></t-radio>
              <t-radio value="F" label="按钮"></t-radio>
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col :span="12" v-if="!['F','CC'].includes(formData.menuType)">
          <t-form-item label="菜单图标" name="icon">
            <t-select
              v-model="formData.icon"
              placeholder="请选择"
              :style="{ width: '400px' }"
              clearable
              :popup-props="{ overlayStyle: { width: '400px' } }"

            >
              <div slot="panelTopContent" style="padding: 6px 6px 0 6px">
                <t-input v-model="search"  placeholder="请输入关键词搜索"  @change="onSearch"  />
              </div>
              <t-option v-for="item in options" :value="item.stem" :key="item.stem" class="overlay-options">
                <div>
                  <t-icon :name="item.stem" />
                </div>
              </t-option>
              <div slot="valueDisplay"><t-icon :name="formData.icon" :style="{ marginRight: '8px' }" />{{ formData.icon }}</div>
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6" >
          <t-form-item label="菜单名称" name="menuName">
            <t-input clearable v-model="formData.menuName"  placeholder="请输入菜单名称"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6" >
          <t-form-item label="显示排序" name="orderNum">
          <t-input-number clearable v-model="formData.orderNum" :min="1" placeholder="请输入"></t-input-number>
          </t-form-item>
        </t-col>
        <t-col :span="6" v-if="!['F','CC'].includes(formData.menuType)">
          <t-form-item label="是否外链" name="isFrame">
            <template slot="label">
              <t-tooltip content="选择是外链则路由地址需要以`http(s)://`开头">
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              是否外链
            </template>
            <t-radio-group v-model="formData.isFrame">
              <t-radio value="0"  label="是"></t-radio>
              <t-radio value="1" label="否"></t-radio>
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col :span="6"  v-if="formData.menuType !== 'F'">
          <t-form-item label="路由地址" name="path">
            <template slot="label">
              <t-tooltip content="访问的路由全地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头">
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              路由地址
            </template>
            <t-input clearable v-model="formData.path"  placeholder="请输入路由地址"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6"  v-if="['C','CC'].includes(formData.menuType)">
          <t-form-item label="路由地址" name="component">
            <template slot="label">
              <t-tooltip content="访问的组件路径，如：`system/user/index`，默认在`pages`目录下">
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              组件路径
            </template>
            <t-input clearable v-model="formData.component"  placeholder="请输入组件路径"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6"  v-if="['CC'].includes(formData.menuType)">
          <t-form-item label="高亮地址" name="activeMenu">
            <template slot="label">
              <t-tooltip content="当前页面的父路由地址">
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              高亮地址
            </template>
            <t-input clearable v-model="formData.activeMenu"  placeholder="请输入高亮地址"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6"  v-if="formData.menuType !== 'M'">
          <t-form-item label="路由地址" name="perms">
            <template slot="label">
              <t-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)">
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              权限字符
            </template>
            <t-input clearable v-model="formData.perms"  :maxlength="100" placeholder="请输入权限字符"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6"  v-if="['C','CC'].includes(formData.menuType)">
          <t-form-item label="路由参数" name="query">
            <template slot="label">
              <t-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`'>
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              路由参数
            </template>
            <t-input clearable v-model="formData.query"  :maxlength="100" placeholder="请输入路由参数"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6" v-if="['C','CC'].includes(formData.menuType)">
          <t-form-item label="是否缓存" name="isCache">
            <template slot="label">
              <t-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致">
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              是否缓存
            </template>
            <t-radio-group v-model="formData.isCache">
              <t-radio value="0"  label="缓存"></t-radio>
              <t-radio value="1" label="不缓存"></t-radio>
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col :span="6" v-if="formData.menuType !== 'F'">
          <t-form-item label="显示状态" name="visible">
            <template slot="label">
              <t-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问">
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              显示状态
            </template>
            <t-radio-group v-model="formData.visible" :options="dict.type.sys_show_hide">
<!--              <t-radio value="0"  label="显示"></t-radio>-->
<!--              <t-radio value="1" label="隐藏"></t-radio>-->
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col :span="6" v-if="formData.menuType !== 'F'">
          <t-form-item label="菜单状态" name="status">
            <template slot="label">
              <t-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问">
                <t-icon name="help-circle-filled"></t-icon>
              </t-tooltip>
              菜单状态
            </template>
            <t-radio-group v-model="formData.status" :options="dict.type.sys_normal_disable">
<!--              <t-radio value="0"  label="正常"></t-radio>-->
<!--              <t-radio value="1" label="停用"></t-radio>-->
            </t-radio-group>
          </t-form-item>
        </t-col>
      </t-row>
    </t-form>
  </t-dialog>
</template>

<script>
import { manifest } from 'tdesign-icons-vue/lib/manifest';
import { listMenu, getMenu, delMenu, addMenu, updateMenu } from "@/api/system/menu";
import {  sysServiceList } from "@/api/system/role";


export default {
  name: "add-edit-menu",
  dicts: ['sys_show_hide', 'sys_normal_disable'],
  props: ['header', 'menuId', 'parentId', 'serviceId'],
  data(){
    return {
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空" }
        ],
        path: [
          { required: true, message: "路由地址不能为空" }
        ],
        component: [
          { required: true, message: "组件路径不能为空" }
        ],
        activeMenu: [
          { required: true, message: "高亮地址不能为空" }
        ]
      },
      search: '',
      options: manifest,
      menuOptions: [],
      visible: true,
      loading: false,
      serviceList:[],
      formData:{
        serviceId: null,
        parentId: null,
        menuName: "",
        icon: "",
        menuType: "M",
        orderNum: 1,
        isFrame: "1",
        isCache: "0",
        visible: "0",
        status: "0",
        activeMenu: ''
      }
    }
  },
  watch: {
    menuId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getObj();
        }
      }
    },
    'formData.menuType':{
      immediate: true,
      handler(val) {
        if (val==='CC') {
          this.formData.isCache = '1'; // 不缓存
          this.formData.visible = '1'; // 隐藏
        }
      }
    },
    // parentId: {
    //   immediate: true,
    //   handler(val) {
    //     if (val) {
    //       this.formData.parentId = val;
    //     }
    //   }
    // }
  },
  created() {
    if (!this.menuId){
      this.getTreeselect();
      // this.getServiceList();
    }
  },
  methods:{
    onSearch() {
      this.options = manifest.filter((item) => item.stem.indexOf(this.search) !== -1);
    },
    getObj(){
      listMenu({serviceId:this.serviceId}).then(response => {
        this.menuOptions = this.handleTree(response.data, "id");
        getMenu(this.menuId).then(response => {
          if (response.data.parentId === 0){
            response.data.parentId = response.data.id;
          }
          this.formData = response.data;
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }).catch((e) => {
        this.$message.error(e.toString());
      });

    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.loading = true;
          if (this.menuId) {
            let {parentId} = this.formData;
            if(this.menuId === this.formData.parentId){
              parentId = 0;
            }
            const row = {...this.formData,parentId,serviceId:this.serviceId}
            updateMenu(row).then((response) => {
              this.$message.success("修改成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              // this.$emit("onRowEdit", row);
              // this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          } else {
            let {parentId} = this.formData;
            if(!this.formData.parentId){
              parentId = 0;
            }
            const row = {...this.formData,parentId,serviceId:this.serviceId}
            addMenu(row).then((response) => {
              this.$message.success("新增成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              // this.$emit("onRowAppendTo",parentId, {...row,id:response.data.id});
              // this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }
        }
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu({serviceId:this.serviceId}).then(response => {
        this.menuOptions = this.handleTree(response.data, "id");
        if(this.parentId>0){
          this.formData.parentId = this.parentId;
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    // 获取微服务列表
    getServiceList() {
      sysServiceList({ pageNum: 1, pageSize: 9999 }).then((res) => {
        this.serviceList = res.rows;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
  }
}
</script>

<style>
.overlay-options {
  display: inline-block;
  font-size: 20px;
}
</style>
